package com.aididi.spring.config;

import com.aididi.spring.entity.BeanDemo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.stereotype.Component;

/**
 * @Auther: zx.xu
 * @Description: 将普通类注册为bean,并将bean讲给ioc容器管理
 */
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor{
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        System.out.println("MyBeanDefinitionRegistryPostProcessor: "+beanDefinitionRegistry);
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(BeanDemo.class);
        beanDefinitionRegistry.registerBeanDefinition("beanDemo",beanDefinition);
    }

    //BeanFactoryPostProcessor:这个接口支持修改容器内的beanDefinition对象，也可以直接注册bean对象，在标准的beanDefinition注册之后以及预实例化bean对象之前
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition("beanDemo");
        beanDefinition.getPropertyValues().addPropertyValue("name","world");

        //还支持直接在bean中注册对象
        BeanDemo beanDemo = new BeanDemo();
        configurableListableBeanFactory.registerSingleton("beanDemo2",beanDemo);
        System.out.println("MyBeanDefinitionRegistryPostProcessor: "+configurableListableBeanFactory);
    }
}
